﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlowBasis.Json;
using System.IO;
using System.Web.Mvc;

namespace FlowBasis.Web.Mvc
{
    public class PostRpcValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            var httpContext = controllerContext.HttpContext;
            var request = httpContext.Request;
            var contentType = request.ContentType;
            if (contentType != null && contentType.StartsWith("application/json"))
            {
                var postBodyReader = new StreamReader(request.InputStream);

                // Other value providers may read the stream, so we need to reset the position to start here.
                postBodyReader.BaseStream.Position = 0;

                var postBody = postBodyReader.ReadToEnd();
                var requestMessage = JObject.Parse(postBody) as JObject;
                if (requestMessage != null)
                {
                    return new PostRpcValueProvider(requestMessage);
                }
            }

            return null;
        }
    }
}
